/*
 * @lc app=leetcode.cn id=95 lang=cpp
 *
 * [95] 不同的二叉搜索树 II
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        if (n == 0) return {};
        return build(1, n);
    }

    vector<TreeNode*> build(int lo, int hi) {
        if (lo > hi) {
            return {nullptr};
        }
        vector<TreeNode*> res;
        for (int i = lo; i <= hi; i++) {
            vector<TreeNode*> left = build(lo, i - 1);
            vector<TreeNode*> right = build(i + 1, hi);
            for (auto& l : left) {
                for (auto& r: right) {
                    TreeNode* cur = new TreeNode(i);
                    cur->left = l;
                    cur->right = r;
                    res.emplace_back(cur);
                }
            }
        }
        return res;
    }
};
// @lc code=end

